import { ReactNode, useRef, useState } from "react";
import SkuAdminForm from "./sku-admin-form";
import SkuAdminTable, { AntdTableData } from "./sku-admin-table";
import { Button } from "antd";
import eventBus from "../eventBus";

export type FormValues = {
  options: { name: string; tags: string[] }[];
};
export type Column = {
  name: string;
};
export type TableData = {
  [key: string]: string;
};
function SkuAdmin() {
  const [columns, setColumns] = useState<Column[]>([]);
  const [data, setData] = useState<TableData[]>([]);
  // test for performance
  // const [count, setCount] = useState(0);

  const [formValues, setFormValues] = useState<FormValues["options"]>([]);
  const handleFormSubmit = (values: FormValues) => {
    setFormValues(values.options);
    createColumns(values);
    createTable(values);
  };

  const createColumns = (values: FormValues) => {
    const columns = values.options.map((v) => {
      return {
        name: v.name
      };
    });
    setColumns(columns);
  };

  const createTable = (values: FormValues) => {
    // create cartesian
    const tagList = values.options.map((v) => v.tags);
    const list = cartesianProduct(tagList);
    // add data key
    const res = addDataKey(list, values);
    setData(res);
  };

  const cartesianProduct = (arrays: string[][]): string[][] => {
    if (arrays.length === 0) {
      return [[]];
    }
    const [firstArray, ...restArrays] = arrays;
    const restProduct = cartesianProduct(restArrays);
    const result = [];
    for (const item of firstArray) {
      for (const product of restProduct) {
        result.push([item, ...product]);
      }
    }
    return result;
  };

  const addDataKey = (res: string[][], values: FormValues) => {
    const data = res.map((item) => {
      const r = item.map((str, idx) => {
        return {
          [values.options[idx].name.toLowerCase()]: str,
        };
      });
      return {
        ...Object.assign({}, ...r),
      };
    });
    return data;
  };

  const handleFinish = (dataSource: AntdTableData[]) => {
    eventBus.emit("createFrontEndPage", { formValues, dataSource });
  };

  return (
    <div style={{padding: '20px'}}>
      <h1>SKU Admin</h1>
      <SkuAdminForm formSubmit={handleFormSubmit} />
      <SkuAdminTable columns={columns} data={data} onFinish={handleFinish}/>
      {/* <Button onClick={() => setCount(count + 1)}>Click me</Button>
      <p>{count}</p> */}
    </div>
  );
}

export default SkuAdmin;
